<template>
  <div class="xtx-pagination">
    <a :class="{disabled: page===1}" @click='changePage(page-1)' href="javascript:;">上一页</a>
    <span v-if='page>3'>...</span>
    <a @click='changePage(item)' :class='{active: page === item}' v-for='item in list' :key='item' href="javascript:;">{{item}}</a>
    <span v-if='page<totalPage-2'>...</span>
    <a :class='{disabled: page===totalPage}' @click='changePage(page+1)' href="javascript:;">下一页</a>
  </div>
</template>
<script>
import { computed, ref } from 'vue'

export default {
  name: 'XtxPagination',
  props: {
    total: {
      type: Number,
      required: true
    },
    pagesize: {
      type: Number,
      default: 10
    }
    // page: {
    //   type: Number,
    //   default: 1
    // }
  },
  setup (props, { emit, attrs }) {
    // attrs表示父组件传递的属性，但是不是props，并且attrs的值不是响应式的
    // console.log(attrs)
    // 计算页码
    // 数据的总条数
    // 每页的条数
    // 当前页码
    const page = ref(attrs.page || 1)
    // 总页数
    const totalPage = Math.ceil(props.total / props.pagesize)
    // 动态计算页码的列表
    const list = computed(() => {
      const pages = []
      if (page.value <= 3) {
        // 开始的数据
        for (let i = 1; i <= totalPage; i++) {
          pages.push(i)
        }
      } else {
        if (props.page <= 3) {
          // 开始的数据
          for (let i = 1; i <= 5; i++) {
            pages.push(i)
          }
        } else if (page.value >= totalPage - 2) {
          // 结束的数据
          for (let i = totalPage - 4; i <= totalPage; i++) {
            pages.push(i)
          }
        } else {
          // 中间的数据
          for (let i = page.value - 2; i <= page.value + 2; i++) {
            pages.push(i)
          }
        }
      }
      return pages
    })

    // 切换页码:修改父组件的当前页码
    const changePage = (currentPage) => {
      // 防止点击上一页和下一页时超出范围
      if (currentPage <= 0 || currentPage > totalPage) return
      // props.page = page
      page.value = currentPage
      // emit('update:page', currentPage)
      // 触发接口调用
      emit('change-page', currentPage)
    }

    return { list, changePage, totalPage, page }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333;
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
